package com.ihg.hiex.admin.handler.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Component;

import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.DateUtils;
import com.ihg.hiex.admin.dao.data.HolidayDao;
import com.ihg.hiex.admin.handler.DateHandler;
import com.ihg.hiex.entity.data.data.HolidayType;

/**
 *
 * @author Ark
 *
 */
@Component("dateHandler")
public class DateHandlerImpl implements DateHandler {
    
    @Dao
    private HolidayDao holidayDao;

    /* (non-Javadoc)
     * @see com.ihg.hiex.admin.handler.DateHandler#calculateWorkDay(java.util.Date, java.lang.String)
     */
    public Date calculateWorkDay(Date date, int scale, String time) {
        
        // 1. list all holiday
        List<Date> holidays = holidayDao.listDay(HolidayType.HOLIDAY);
        List<Date> workdays = holidayDao.listDay(HolidayType.WORKDAY);
        
        // 2. calculate work day
        Date startDate = date;
        int days = 0;               // 判断是否是假期日或周末，如果是，天数加1
        for (int i = 0; i < scale; i++) {
            
            date = org.apache.commons.lang3.time.DateUtils.addDays(date, -1);
            
            if (DateUtils.isWeekend(date)) {        // 周末

                if (!this.contains(workdays, date)) {
                    days++;
                }
                
            } else {                                // 工作日
                
                if (this.contains(holidays, date)) {
                    days++;
                }
                
            }
            
        }
        
        // 3. Determine scaleDay whether weekend or holiday
        scale = scale + days;
        Date resultDate = org.apache.commons.lang3.time.DateUtils.addDays(startDate, -scale);
        for (int i = 0; i < 20; i++) {
            
            if (!DateUtils.isWeekend(resultDate) && !this.contains(holidays, resultDate)) {
                break;
            } else {
                resultDate = org.apache.commons.lang3.time.DateUtils.addDays(resultDate, -1);
            }
            
        }
        
        Date result = DateUtils.parseDate(DateFormatUtils.format(resultDate, "yyyy-MM-dd") + " " + time, "yyyy-MM-dd HH:mm");
        return result;
        
    }
    
    /**
     * Determine current whether in dateList
     * 
     * @param dateList
     * @param now
     * @return
     */
    private boolean contains(List<Date> dateList, Date now) {
        
        for (Date date : dateList) {
            if (DateUtils.isSameDay(date, now)) {
                return true;
            }
        }
        
        return false;
        
    }
    
}
